<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate">
        {{ $t('table.add') }}
      </el-button>
    </div>
    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row
              style="width: 100%;" @sort-change="sortChange">
      <el-table-column label="ID" prop="carouselId" sortable="custom" align="center" width="80"
                       :class-name="getSortClass('carouselId')">
        <template slot-scope="{row}">
          <span>{{ row.carouselId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片名称" prop="carouselName" sortable="custom" align="center" width="180">
        <template slot-scope="{row}">
          <span>{{ row.carouselName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" prop="carouselUrl" sortable="custom" align="center" width="200">
        <template slot-scope="{row}">
          <el-image style="width: 180px; height: 180px" :src="row.carouselUrl" fit="contain"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="图片描述" prop="carouselDescription" sortable="custom" align="center" width="180">
        <template slot-scope="{row}">
          <span>{{ row.carouselDescription }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="210"
                       class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('table.edit') }}
          </el-button>
          <el-button v-if="row.status != 'deleted'" size="mini" type="danger"
                     @click="handleDelete(row, $index)">
            {{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px"
               style="width: 400px; margin-left:50px;">
        <el-form-item label="轮播图ID">
          <el-input v-model="temp.carouselId" :autosize="{ minRows: 2, maxRows: 4 }" retype="text"
                    readonly="" />
        </el-form-item>
        <el-form-item label="图片名称">
          <el-input v-model="temp.carouselName" :autosize="{ minRows: 2, maxRows: 4 }" type="text"
                    placeholder="请输入图片名称" />
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload :action="uploadUrl" list-type="picture-card" :on-preview="handlePictureCardPreview"
                     :on-remove="handleRemove" :on-success="handleUploadSuccess" :before-upload="beforeUpload"
                     :file-list="temp.fileList">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="图片描述">
          <el-input v-model="temp.carouselDescription" :autosize="{ minRows: 2, maxRows: 4 }" type="text"
                    placeholder="请输入图片描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { findByPage, fetchCarouselList, addCarousel, updateCarousel, deleteCarousel } from '@/api/carousel'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {},
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
      },
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      temp: {
        carouselId: undefined,
        carouselName: "",
        carouselUrl: "",
        carouselDescription: ""
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      uploadUrl: 'api/shop/carousel/upload',
      dialogImageUrl: '',
      dialogVisible: false,
      rules: {
        carouselName: [{ required: true, message: '图片名字不能为空', trigger: 'blur' }],
        carouselDescription: [{ required: true, message: '图片描述不能为空', trigger: 'blur' }]
      }
    }
  },

  created() {
    this.getList();
  },

  methods: {
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return (isJPG || isPNG) && isLt2M;
    },

    handleUploadSuccess(response, file, fileList) {
      this.temp.carouselUrl = response.url;
      this.$message.success('图片上传成功');
    },
    handleRemove(file, fileList) {
      this.temp.carouselUrl = '';
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    getList() {
      this.listLoading = true;
      findByPage(this.listQuery).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 100);
      });
    },

    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },

    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      });
      row.status = status;
    },

    resetTemp() {
      this.temp = {
        carouselId: undefined,
        carouselName: "",
        carouselUrl: "",
        carouselDescription: ""
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = 'create';
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate();
      });
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addCarousel(this.temp).then(response => {
            this.getList();
            this.dialogFormVisible = false;
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            });
          });
        }
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row);
      this.dialogStatus = 'update';
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate();
      });
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp);
          updateCarousel(tempData).then(() => {
            this.getList();
            this.dialogFormVisible = false;
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            });
          });
        }
      });
    },
    handleDelete(row, index) {
      deleteCarousel(row.carouselId).then(() => {
        this.getList();
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        });
      });
    },

    getSortClass(key) { // 获取排序类名
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? 'ascending' : 'descending';
    }
  }
}
</script>

